#include <WiFi.h>

const char* host     = "192.168.9.104"; // TCP服务器IP
const uint16_t port  = 5002;            // TCP服务器端口

WiFiClient client;
int isConnected = 0;
int sendCount = 0;

int tcp_connect() {
  const unsigned long RECONNECT_INTERVAL = 10000; // 10 秒重试
  while (true) {
    Serial.printf("Connect to TCP Server %s:%d...", host, port);
    if (!client.connect(host, port)) {
      Serial.println("tcp connected failed, will retry...");
      delay(RECONNECT_INTERVAL);
      continue; // 再试
    }
    Serial.println("tcp connected success!");
    isConnected = 1;

    // 获取 64 位芯片 ID 和 MAC
    uint64_t chipid = ESP.getEfuseMac();
    String mac = WiFi.macAddress();
    Serial.printf("Chip ID (64-bit): %llX\n", chipid);
    Serial.print("Station MAC: ");
    Serial.println(mac);

    // 发送标识信息
    String msg = "{";
    msg += "\"mac\":\"" + mac + "\",";
    msg += "\"chipid\":\"" + String((uint32_t)(chipid >> 32), HEX) + String((uint32_t)chipid, HEX) + "\"";
    msg += "}\n";
    client.print(msg);
    Serial.print("Sent: ");
    Serial.println(msg);

    // 等待服务器返回 ok
    unsigned long startTime = millis();
    while (millis() - startTime < 3000) {
      if (client.available()) {
        String response = client.readStringUntil('\n');
        response.trim();
        Serial.print("Received: ");
        Serial.println(response);

        if (response.equalsIgnoreCase("ok")) {
          Serial.println("Handshake OK, ready to communicate.");
          return 1;
        } else {
          Serial.println("Unexpected response, closing connection.");
          client.stop();
          break;
        }
      }
    }

    Serial.println("timeout, will retry...");
    client.stop();
    delay(RECONNECT_INTERVAL);
  }
}

void tcp_send_string(String msg){
  sendCount++;
  if(isConnected == 0) {
    return;
  }

  client.print(msg);
  Serial.printf("count: %d, already send: %d\n", sendCount, msg.length());
}

void tcp_send_bytes(uint8_t* buff, int length){
  if (!client.connected()) {
    Serial.println("TCP disconnected, reconnecting...");
    isConnected = 0;
    tcp_connect();
  }

  sendCount++;
  if(isConnected == 0) {
    return;
  }
  client.write(buff, length);
  // Serial.printf("count: %d, 已发送字节: %d\n", count, length);
}